package main

import (
	"fmt"
)

type Node struct {
	Data int
	Next *Node
}
type SingleLinkedList struct {
	head *Node // 头节点，不存数据
	size int   // 大小
}

func NewSingleLinkedList() *SingleLinkedList {
	return &SingleLinkedList{
		head: &Node{},
		size: 0,
	}
}
func (a *SingleLinkedList) Add(value int) {
	t := a.head
	for {
		if t.Next == nil {
			break
		}
		t = t.Next
	}
	t.Next = &Node{Data: value, Next: nil}
	a.size++
}
func (a *SingleLinkedList) Remove(value int) bool {
	t := a.head
	for {
		if t.Next != nil && t.Next.Data == value {
			// remove
			t2 := t.Next
			t.Next = t.Next.Next
			t2.Next = nil
			t2 = nil
			a.size-- // 大小减去一个
			return true
		}
		t = t.Next
		if t == nil {
			break
		}
	}
	return false
}
func (a *SingleLinkedList) Contains(value int) bool {
	t := a.head.Next
	for {
		if t == nil {
			break
		}
		if t != nil && t.Data == value {
			return true
		}
		t = t.Next
	}
	return false
}
func (a *SingleLinkedList) GetWithIndex(index int) (int, bool) {
	if index < 0 {
		return -1, false
	}
	if index >= a.size { // size=10 index is 0-9
		return -1, false
	}
	t := a.head
	for i := 0; i <= index; i++ {
		t = t.Next
	}
	return t.Data, true
}
func (a *SingleLinkedList) IsEmpty() bool {
	return a.size == 0
}
func (a *SingleLinkedList) Size() int {
	return a.size
}
func (a *SingleLinkedList) PrintList() {
	t := a.head.Next
	for {
		if t == nil {
			break
		}
		fmt.Printf("=>{%d}", t.Data)
		t = t.Next
	}
	fmt.Printf("\n")
}

func main() {
	list := NewSingleLinkedList()
	fmt.Println("isEmpty:", list.IsEmpty())
	for i := 1; i < 10; i++ {
		list.Add(i)
	}
	list.PrintList()
	list.Remove(5)
	list.Remove(9)
	list.PrintList()
	fmt.Println("isEmpty:", list.IsEmpty())
	fmt.Println(list.Size())
	fmt.Println(list.Contains(100), list.Contains(8))
	fmt.Println(list.GetWithIndex(8))
}
